<?php

namespace app\admin\controller;

use app\admin\middleware\CheckAdmin;
use app\BaseController;
use app\common\BusinessException;
use think\facade\Db;

class Role extends BaseController
{

    protected $middleware = [
        CheckAdmin::class,
    ];

    public function index()
    {
        // 获取角色列表 分页
        $pageNum = $this->request->param('pageNum', 1);
        $pageSize = $this->request->param('pageSize', 10);

        $list = Db::name('role')
            ->where('status', 1)
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $pageNum,
            ]);

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $list,
        ]);

    }

    /**
     * 创建角色
     */
    public function create()
    {
        $name = $this->request->param('name');

        if (empty($name)) {
            throw new BusinessException('角色名称不能为空');
        }

        // 检查角色名称是否已存在
        $role = Db::name('role')->where('name', $name)->find();
        if ($role) {

            throw new BusinessException('角色名称已存在');

        }

        // 创建角色
        $role = Db::name('role')->insert([
            'name' => $name,
            'status' => 1,

        ]);

        $lastId = Db::name('role')->getLastInsID();

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $lastId,
        ]);

    }

    public function permissions()
    {
        $roleId = $this->request->param('roleId');

        $role = Db::name('role')->where('id', $roleId)->find();

        if (!$role) {
            throw new BusinessException('角色不存在');
        }

        // 关联查询出role的所有权限
        $permissions = Db::name('role')
            ->alias('r')
            ->join('rolepermission rp', 'r.id = rp.roleId')
            ->join('permission p', 'rp.permissionId = p.id')
            ->where('r.id', $roleId)
            ->field('p.*')
            ->select();

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                "role" => $role,
                'permissions' => $permissions,
            ],
        ]);

    }

    /**
     * 给角色分配权限
     */
    public function assignPermissions()
    {
        $roleId = $this->request->post('roleId');
        $permissionIds = $this->request->post('permissionIds');

        if (empty($roleId)) {
            throw new BusinessException('角色ID不能为空');
        }

        if (empty($permissionIds)) {
            throw new BusinessException('权限ID不能为空');
        }

        // 检查角色是否存在
        $role = Db::name('role')->where('id', $roleId)->find();
        if (!$role) {
            throw new BusinessException('角色不存在');
        }

        // 将字符串格式的permissionIds转换为数组
        $permissionIds = explode(',', $permissionIds);
        // 将数组中的每个元素转换为整数
        $permissionIds = array_map('intval', $permissionIds);
        $permissionList = $permissionIds;

        // $permissionList
        // 查询用户当前绑定的权限
        $currentPermissions = Db::name('role')
            ->alias('r')
            ->join('rolepermission rp', 'r.id = rp.roleId')
            ->join('permission p', 'rp.permissionId = p.id')
            ->where('r.id', $roleId)
            ->field('p.id')
            ->select()->toArray();

        // 转换为数组
        $currentPermissionIds = array_column($currentPermissions, 'id');
        // 计算需要添加的权限
        $addPermissions = array_diff($permissionList, $currentPermissionIds);
        // 计算需要删除的权限
        $deletePermissions = array_diff($currentPermissionIds, $permissionList);

        // 新增权限
        if (!empty($addPermissions)) {
            foreach ($addPermissions as $permissionId) {
                Db::name('rolepermission')->insert([
                    'roleId' => $roleId,
                    'permissionId' => $permissionId,
                ]);
            }
        }

        // 删除权限
        if (!empty($deletePermissions)) {
            foreach ($deletePermissions as $permissionId) {
                Db::name('rolepermission')->where('roleId', $roleId)->where('permissionId', $permissionId)->delete();
            }
        }

        return json([
            'code' => 200,
            'msg' => '角色权限配置成功',
            "data" => null,
        ]);

    }

}
